package com.ebt.m.utils;

import android.text.TextUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

//import net.sourceforge.jeval.function.string.CompareTo;

public class TimeUtils {
    private static final String tag = "DateUtils";
    public static final String MM_DD = "MM-dd";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final String HH_MM_SS = "HH:mm:ss";
    public static final String HH_MM = "HH:mm";
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD_HH_MM_SS_REVER = "yyyy/MM/dd HH:mm:ss";
    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static final String YYYY_MM_DD_HH_MM_SS_S = "yyyy-MM-dd HH:mm:ss.S";
    private static SimpleDateFormat mDateFormat = new SimpleDateFormat(
            YYYY_MM_DD, Locale.getDefault());

    public TimeUtils() {

    }

    /**
     * 获取当前时间用于填充本地数据库的createTime字段
     *
     * @return
     */
    public static String getCurrentTime() {
        return dateTime2String(Calendar.getInstance(Locale.getDefault())
                .getTime());
    }

    /**
     * 获取当前时间用于填充本地数据库的createTime字段
     *
     * @return
     */
    public static Date getCurrentTimeDate() {
        return stringToDateTime(dateTime2String(Calendar.getInstance(
                Locale.getDefault()).getTime()));
    }

    // public static Date getTime(){
    // return Calendar.getInstance(Locale.getDefault()).getTime();
    // }

    /**
     * 将日期转化为字符串
     *
     * @param date
     * @return
     */
    public static String dateTime2String(Date date) {
        if (null == date) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS,
                Locale.getDefault());
        return sdf.format(date);
    }

    /**
     * 将日期格式化
     *
     * @param date
     * @param formater
     * @return
     */
    public static Date formatDate(Date date, String formater) {
        if (null == date) {
            return null;
        }
        if (TextUtils.isEmpty(formater)) {
            formater = YYYY_MM_DD;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(formater);

        return stringToDateTime(sdf.format(date));
    }

    /**
     * 将日期转化为字符串
     *
     * @param date
     * @param formater
     * @return
     */
    public static String dateTime2String(Date date, String formater) {
        if (null == date) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(formater);
        return sdf.format(date);
    }

    /**
     * 将字符串转化为日期
     *
     * @param s
     * @return
     */
    public static Date stringToDateTime(String s) {
        if (DataValidation.isEmpty(s)) {
            return null;
        }
        try {
            SimpleDateFormat sdf;
            if (s.matches("\\d{4}-\\d{2}-\\d{2}")) {
                sdf = new SimpleDateFormat(YYYY_MM_DD);
            } else if (s.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
            } else if (s
                    .matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3}")) {
                sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS_S);
            } else if (s.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                // SimpleDateFormat dateFormat = new
                // SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
                sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS_REVER);
            } else {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            }

            return sdf.parse(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * string转化为calendar
     *
     * @param str
     * @return
     */
    public static Calendar parseStrToCld(String str) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(stringToDateTime(str));
        return calendar;
    }

    /**
     * calendar 转化为字符串
     *
     * @return
     */
    public static String getFormatCld(Calendar cal) {
        return dateTime2String(cal.getTime());
    }

    /*
     * 根据给定的long型时间获得时间字符串
     */
    public static String getDateStrByLong(long timeInMillis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeInMillis);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String result = sdf.format(cal.getTime());
        return result;
    }

    public static String getDateStrByLong(String pattern, long timeInMillis) {
        if (timeInMillis == 0.0) {
            return "-";
        }
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeInMillis);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String result = sdf.format(cal.getTime());
        return result;
    }

    /**
     * 根据生日获得年龄
     *
     * @param birthDay
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay) {
        if (birthDay == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }

        return age;
    }

    /**
     * 获取生日和当前日期的天数
     *
     * @param birthDay
     * @return
     */
    public static int getAgeDays(Date birthDay) {
        if (birthDay == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            return 0;
        }
        long nowTime = cal.getTimeInMillis();
        cal.setTime(birthDay);
        long birthTime = cal.getTimeInMillis();
        long between_days = (nowTime - birthTime) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 获取两个日期相差月数
     *
     * @param date1
     * @param date2
     * @return
     * @throws ParseException
     */
    public static int getMonthSpace(String date1, String date2)
            throws ParseException {

        int result = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(sdf.parse(date1));
        c2.setTime(sdf.parse(date2));

        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        return result;
    }

    /**
     * 获取两个日期相差月数
     *
     * @param date1
     * @param date2
     * @return
     * @throws ParseException
     */
    public static int getMonthSpace(Date date1, Date date2) {

        int result = 0;

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(date1);
        c2.setTime(date2);

        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);

        return result;

    }

    /**
     * 获取两个日期相差天数
     *
     * @return
     * @throws ParseException
     */

    public static final long daysBetween(Date early, Date late) {

        Calendar calst = Calendar.getInstance();
        Calendar caled = Calendar.getInstance();
        calst.setTime(early);
        caled.setTime(late);
        // 设置时间为0时
        calst.set(Calendar.HOUR_OF_DAY, 0);
        calst.set(Calendar.MINUTE, 0);
        calst.set(Calendar.SECOND, 0);
        caled.set(Calendar.HOUR_OF_DAY, 0);
        caled.set(Calendar.MINUTE, 0);
        caled.set(Calendar.SECOND, 0);
        // 得到两个日期相差的天数
        long days = ((caled.getTime().getTime() / 1000) - (calst.getTime()
                .getTime() / 1000)) / 3600 / 24;
        return days;
    }

    //
    // /**
    // * 根据生日获得从出生到现在的月数差
    // *
    // * @param birthDay
    // * @return
    // * @throws Exception
    // */
    // public static int getMonthsFromBirthday(Date birthDay) {
    // if (birthDay == null) {
    // return 0;
    // }
    // Calendar cal = Calendar.getInstance();
    //
    // if (cal.before(birthDay)) {
    // throw new
    // IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
    // }
    //
    // int yearNow = cal.get(Calendar.YEAR);
    // int monthNow = cal.get(Calendar.MONTH);
    // int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
    // cal.setTime(birthDay);
    //
    // int yearBirth = cal.get(Calendar.YEAR);
    // int monthBirth = cal.get(Calendar.MONTH);
    // int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
    //
    // int age = yearNow - yearBirth;
    //
    // if (monthNow <= monthBirth) {
    // if (monthNow == monthBirth) {
    // if (dayOfMonthNow < dayOfMonthBirth) {
    // age--;
    // }
    // } else {
    // age--;
    // }
    // }
    //
    // return age;
    // }

    /**
     * 获得某天某点
     *
     * @param date
     * @return
     */
    public static Date getTimeDate(Date date, int hour, int minute, int second) {
        Calendar c = Calendar.getInstance();
        c.set(date.getYear() + 1900, date.getMonth(), date.getDate(), hour,
                minute, second);
        return c.getTime();
    }

    /**
     * 根据年龄获取生日
     *
     * @param age
     * @return
     */
    public static Date getBirthday(int age) {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        calendar.add(Calendar.YEAR, -age);
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD,
                Locale.getDefault());
        Date result = stringToDateTime(sdf.format(calendar.getTime()));
        return result;
    }

    /**
     * 获取用于数据库比较的日期 昨天、最近一周、最近一个月、
     *
     * @param field Calendar.DAY_OF_MONTH、 Calendar.WEEK_OF_MONTH 、Calendar.MONTH
     * @return "2013-07-29"
     */
    public static String getCompareDate(int field) {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        switch (field) {
            case Calendar.DAY_OF_MONTH:
            case Calendar.WEEK_OF_MONTH:
            case Calendar.MONTH:
                calendar.add(field, -1);
                break;
            default:
                break;
        }
        return mDateFormat.format(calendar.getTime());
    }

    /**
     * 获取默认生日
     *
     * @return
     */
    public static String getDefaultBrithday() {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        calendar.add(Calendar.MONTH, -3);
        calendar.add(Calendar.YEAR, -30);
        return mDateFormat.format(calendar.getTime());
    }

    /**
     * yyyy-MM-dd 获得生日字符串
     *
     * @param date
     * @return
     */
    public static String getBrithday(Date date) {
        if (date == null) {
            return getDefaultBrithday();
        }
        return mDateFormat.format(date);
    }

    /**
     * @param date
     * @param year 加减年
     * @return
     */
    public static String calculate(String date, int year) {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        calendar.setTime(stringToDateTime(date));
        calendar.add(Calendar.YEAR, year);

        return mDateFormat.format(calendar.getTime());
    }

    /**
     * @param date
     * @param num  加减天
     * @return
     */
    public static Date dayPlusOrMinus(Date date, int num) {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        calendar.setTime(date);
        calendar.add(Calendar.DATE, num);
        return calendar.getTime();
    }

    /**
     * 两个日期字符串的比较
     *
     * @param time1
     * @param time2
     * @return 0 if the times of the two Calendars are equal, -1 if the time of
     * this Calendar is before the other one, 1 if the time of this
     * Calendar is after the other one.
     */
    public static int timeCompare(String time1, String time2) {
        DateFormat df = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        Calendar c1 = Calendar.getInstance(Locale.getDefault());
        Calendar c2 = Calendar.getInstance(Locale.getDefault());
        try {
            c1.setTime(df.parse(time1));
            c2.setTime(df.parse(time2));
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return c1.compareTo(c2);
    }

    /**
     * 比较日期（年月日） 0:相等 -1:小于 1:大于 不比较时分秒
     *
     * @param left
     * @param right
     * @return
     */
    public static int compareDate(Date left, Date right) {
        // Log.i("--left--", "left is "+dateTime2String(left));
        // Log.i("--right--", "right is "+dateTime2String(right));
        Calendar temp = Calendar.getInstance(Locale.getDefault());
        Calendar c1 = Calendar.getInstance(Locale.getDefault());
        Calendar c2 = Calendar.getInstance(Locale.getDefault());
        c1.setTime(temp.getTime());
        c2.setTime(temp.getTime());

        temp.setTime(left);
        c1.set(temp.get(Calendar.YEAR), temp.get(Calendar.MONTH),
                temp.get(Calendar.DAY_OF_MONTH));
        temp.setTime(right);
        c2.set(temp.get(Calendar.YEAR), temp.get(Calendar.MONTH),
                temp.get(Calendar.DAY_OF_MONTH));
        // Log.i("--c1--", "c1 is "+getFormatCld(c1));
        // Log.i("--c2--", "c2 is "+getFormatCld(c2));
        return c1.compareTo(c2);
    }

    /**
     * 与今天相比较 0:相等 -1:小于 1:大于. 只比较年月日
     *
     * @param date
     * @return
     */
    public static int compareToday(Date date) {
        Date current = Calendar.getInstance(Locale.getDefault()).getTime();
        return compareDate(date, current);
    }

    /**
     * 与今天相比较 0:相等 -1:小于 1:大于
     *
     * @return
     */
    public static int compareTodayTime(long dateTime) {
        Long currentTime = Calendar.getInstance(Locale.getDefault()).getTime()
                .getTime();
        return -currentTime.compareTo(dateTime);
    }

    /**
     * @param
     * @return int
     * @throws
     * @Description: 获得当月天数
     */
    public static int getMonthDays() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DATE, 1);
        c.roll(Calendar.DATE, -1);
        int num = c.get(Calendar.DATE);
        return num;
    }

    /**
     * @param
     * @return int
     * @throws
     * @Description: 获得两个日期之间的天数
     */
    public static int getDateInterval(Date start, Date end) {
        long quot;
        quot = end.getTime() - start.getTime();
        quot = quot / 1000 / 60 / 60 / 24;
        int day = new Long(quot).intValue();
        return day;
    }

    /**
     * @param
     * @return int
     * @throws
     * @Description: 获得两个时间之间的间隔，单位小时
     */
    public static int getDateIntervalByHour(Date start, Date end) {
        long quot;
        quot = end.getTime() - start.getTime();
        quot = quot / 1000 / 60 / 60;
        int hours = new Long(quot).intValue();
        return hours;
    }

    /**
     * @param
     * @return int
     * @throws
     * @Description: 获得两个时间之间的间隔，单位分
     */
    public static int getDateIntervalByMinute(Date start, Date end) {
        long quot;
        quot = end.getTime() - start.getTime();
        quot = quot / 1000 / 60;
        int minute = new Long(quot).intValue();
        return minute;
    }

    /**
     * 是否是同一天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDay(Date date1, Date date2) {
        boolean resulte = false;
        if (date1.getYear() == date2.getYear()
                && date1.getMonth() == date2.getMonth()
                && date1.getDate() == date2.getDate()) {
            resulte = true;
        }
        return resulte;
    }

    /**
     * 将yyyy/MM/d hh:mm:ss或yyyy-MM-d hh:mm:ss 非标准转化成 yyyy-MM-dd hh:mm:ss格式
     *
     * @param dateStr
     * @return
     */
    public static String changeDateFormat(String dateStr) {
        String resulte = null;

        if (dateStr == null) {
            return null;
        }
        dateStr = dateStr.replace("T", " ");

        String y = "";
        String M = "";
        String d = "";
        String h = "";

        String m = "";

        String s = "";

        String sqlit = "";

        if (dateStr != null && !dateStr.isEmpty()) {
            if (dateStr.contains("/")) {
                sqlit = "/";
            } else if (dateStr.contains("-")) {
                sqlit = "-";
            } else {
                return null;
            }
        } else {
            return null;
        }
        try {
            String[] datearray = dateStr.split(" ");

            if (datearray.length == 1) {

                String date = datearray[0];
                String[] dates = date.split(sqlit);
                y = dates[0];
                M = dates[1];
                d = dates[2];

                if (y.length() < 4) {
                    return null;
                }
                int _M = Integer.parseInt(M);
                int _d = Integer.parseInt(d);
                if (_M < 10) {
                    M = "0" + _M;
                }
                if (_d < 10) {
                    d = "0" + _d;
                }

                h = "00";
                m = "00";
                s = "00";
            } else if (datearray.length == 2) {

                String date = datearray[0];
                String time = datearray[1];

                String[] dates = date.split(sqlit);
                y = dates[0];
                M = dates[1];
                d = dates[2];
                if (y.length() < 4) {
                    return null;
                }
                int _M = Integer.parseInt(M);
                int _d = Integer.parseInt(d);
                if (_M < 10) {
                    M = "0" + _M;
                }
                if (_d < 10) {
                    d = "0" + _d;
                }

                String[] times = time.split(":");
                if (times.length == 3) {
                    h = times[0];
                    m = times[1];
                    s = times[2];
                    int _h = Integer.parseInt(h);
                    int _m = Integer.parseInt(m);
                    int _s = (int) Double.parseDouble(s);
                    if (_h < 10) {
                        h = "0" + _h;
                    }
                    if (_m < 10) {
                        m = "0" + _m;
                    }
                    if (_s < 10) {
                        s = "0" + _s;
                    } else {
                        s = _s + "";
                    }

                } else if (times.length == 2) {
                    h = times[0];
                    m = times[1];

                    int _h = Integer.parseInt(h);
                    int _m = Integer.parseInt(m);

                    if (_h < 10) {
                        h = "0" + _h;
                    }
                    if (_m < 10) {
                        m = "0" + _m;
                    }
                    s = "00";
                } else {
                    h = "00";
                    m = "00";
                    s = "00";
                }

            } else {
                return null;
            }
            resulte = y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;

        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return resulte;
    }

    /**
     * @param d1
     * @param d2
     * @return int
     * @throws
     * @Description: 比较两个日期
     */
    public static int compareTwoDate(Date d1, Date d2) {
        if (d1 == null && d2 == null) {
            return 0;
        }
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(d1);
            c2.setTime(d2);
        } catch (Exception e) {
            return -10;
        }
        return c1.compareTo(c2);
    }

    /**
     * 根据日期获得星期
     *
     * @param date
     * @return
     */
    public static String getWeekOfDate(Date date) {
        String[] weekDaysName = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
                "星期六"};
//		String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDaysName[intWeek];
    }

    public static String getStringByDuration(long mills) {
        String str = "";
        if (mills / 60 > 0) {
            str = mills / 60 + "分";
        }
        if (mills % 60 > 0) {
            str += mills % 60 + "秒";
        }
        return str;
    }

    public static String getMessageDate(String date) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
            return simpleDateFormat.format(dateFormat.parse(date));
        } catch (Exception e) {
            return date;
        }
    }
}
